package com.yuns.exam.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.mysql.jdbc.StringUtils;
import com.yuns.exam.entity.ExamAnswerRecord;
import com.yuns.exam.req.ExamAnswerRecordReq;
import com.yuns.exam.req.ExamRecordParm;
import com.yuns.exam.req.QuestionParam;
import com.yuns.exam.service.IExamAnswerRecordService;
import com.yuns.exam.service.IExamRecordService;
import com.yuns.exam.entity.ExamRecord;
import com.yuns.exam.vo.CertificateVO;
import com.yuns.exam.vo.ExamErrorData;
import com.yuns.exam.vo.ExamRecordVO;
import com.yuns.exam.vo.QuestionVO;
import com.yuns.exception.MyException;
import com.yuns.util.DateUtils;
import com.yuns.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.ApiOperation;
import com.yuns.web.param.FrontPage;
import com.yuns.util.ResultJson;
import io.swagger.annotations.Api;
import com.baomidou.mybatisplus.plugins.Page;
import com.yuns.web.param.QueryParam;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//import com.yuns.web.dto.ExamRecordDto;


/**
 * @author ${author}
 * @since 2020-10-25
 */
@Api(tags = "考试记录表 - Controller" )
    @RestController
@RequestMapping("/examRecord" )
    public class ExamRecordController {

    @Autowired
    private IExamRecordService iExamRecordService;

    @Autowired
    IExamAnswerRecordService examAnswerRecordService;

    @ApiOperation(value = "添加 - gt_exam_record" )
    @PostMapping(value = "insert" )
    public ResultJson insert(@RequestBody ExamRecord model){
            //  ExamRecord entity=DtoUtil.convertObject(model,ExamRecord.class);
            boolean flag=iExamRecordService.insert(model);
            if(flag){
            return ResultJson.ok();
            }else{
            return ResultJson.error();
            }
            }

    @ApiOperation(value = "修改 - gt_exam_record" )
    @PostMapping(value = "up/{id}" )
    public ResultJson update(@RequestBody ExamRecord model){
            //ExamRecord entity=DtoUtil.convertObject(model,ExamRecord.class);
            boolean flag=iExamRecordService.updateById(model);
            if(flag){
            return ResultJson.ok();
            }else{
            return ResultJson.error();
            }
            }

    @ApiOperation(value = "删除 - gt_exam_record" )
    @PostMapping(value = "delete/{id}/{examinationInfoID}" )
    public ResultJson delete(@PathVariable("id") Integer id ,
                             @PathVariable("examinationInfoID") String examinationInfoID){

        if(examinationInfoID==null || StringUtils.isNullOrEmpty(examinationInfoID)){
            throw  new MyException("请传试卷id 或者ExaminationInfoID");
        }
            boolean flag=iExamRecordService.deleteById(String.valueOf(id));
        Map m = new HashMap();
        m.put("exam_record_id",id);// 答案记录对应唯一的考试记录
        m.put("exam_title_id",examinationInfoID);
        examAnswerRecordService.deleteByMap(m);
            if(flag){
            return ResultJson.ok();
            }else{
            return ResultJson.error();
            }
            }

    @ApiOperation(value = "查询所有 - gt_exam_record" )
    @PostMapping(value = "query" )
    public ResultJson query(@RequestBody ExamRecordParm frontPage){

            ExamRecordVO examRecordVO = frontPage.getData();
            examRecordVO.setIsCheck(1);
            Object list=iExamRecordService.selectExamRecordList(frontPage);
            return ResultJson.ok(list);
            }

    @ApiOperation(value = "阅卷（给简答题评分） - gt_exam_record" )
    @PostMapping(value = "checkPageForQuestion" )
    public ResultJson checkPageForQuestion(@RequestBody FrontPage<ExamAnswerRecord> frontPage){
        String examid = frontPage.getData().getExamTitleId();
        String recordid =         frontPage.getData().getExamRecordId();
        String id = String.valueOf(frontPage.getData().getId());

        ExamAnswerRecord examAnswerRecord = ExamAnswerRecord.builder().build();
        examAnswerRecord.setExamRecordId(recordid);
        examAnswerRecord.setExamTitleId(examid);
        EntityWrapper<ExamAnswerRecord> examAnswerRecordEntityWrapper  = new EntityWrapper<>();
        examAnswerRecordEntityWrapper.setEntity(examAnswerRecord);
       List<ExamAnswerRecord> examAnswerRecords =
               examAnswerRecordService.selectList(examAnswerRecordEntityWrapper);

//        Double salesAmount = examAnswerRecords.stream().map(o ->
//                BigDecimal.valueOf(o.getScore()-ArithUtils.add(o.getScore(), o.getScore()))).
//                reduce(BigDecimal::add).orElse(BigDecimal.ZERO).doubleValue();
//        examAnswerRecord.setQuestionType(3);//只更新简答题题
//        examAnswerRecord.setScore(frontPage.getData().getScore());

//        Double  salesAmount=examAnswerRecords.stream().mapToDouble(ExamAnswerRecord::getScore).sum();


        examAnswerRecord.setId(Long.valueOf(id));
        examAnswerRecord.setScore(frontPage.getData().getScore());
        BigDecimal totalGrade =
                examAnswerRecords.stream().map(ExamAnswerRecord::getScore).reduce(BigDecimal::add).get();
        // 更新分数到题目记录
        examAnswerRecordService.updateById(examAnswerRecord);
        totalGrade = totalGrade.add(frontPage.getData().getScore());
        ExamRecord t = ExamRecord.builder().isCheck(1).id(recordid).build();
        t.setScore(totalGrade);
        // 更新总分到考试记录
         Boolean r = iExamRecordService.updateById(t);

        return ResultJson.ok(r);
    }


        //*****************门户的接口*****************************/

    @ApiOperation(value = "开始考试" )
    @PostMapping(value = "beginExam" )
    public ResultJson beginExam(@RequestBody ExamRecordVO examRecordVO){
        Object t =  iExamRecordService.beginExam(examRecordVO);
        return  ResultJson.ok(t);
    }

    @ApiOperation(value = "做题接口" )
    @PostMapping(value = "updateExamAnswerRecord" )
    public ResultJson updateExamAnswerRecord(@RequestBody ExamAnswerRecord examAnswerRecord){
        Object t =  iExamRecordService.updateExamAnswerRecord(examAnswerRecord);
        return  ResultJson.ok(t);
    }

    @ApiOperation(value = "提交试卷" )
    @PostMapping(value = "submitExam" )
    public ResultJson submitExam(@RequestBody ExamRecordVO examRecordVO){
        Object t =  iExamRecordService.submitExam(examRecordVO);
        return  ResultJson.ok(t);
    }

    @ApiOperation(value = "错题集统计" )
    @PostMapping(value = "selectErrorQuestionList" )
    public  ResultJson selectErrorQuestionList(@RequestBody ExamAnswerRecordReq examAnswerRecordReq){
        List<ExamErrorData>  r =  examAnswerRecordService.selectErrorQuestionList(examAnswerRecordReq);
        return ResultJson.ok(r);
    }

    @ApiOperation(value = "根据错题集类型查找错题列表" )
    @PostMapping(value = "selectErrorQuestionListByQuestionType" )
    public  ResultJson selectErrorQuestionListByQuestionType(@RequestBody QuestionParam frontPage){
        Object  r =  iExamRecordService.selectErrorQuestionListByQuestionType(frontPage);
        return ResultJson.ok(r);
    }

    @ApiOperation(value = "模拟考试" )
    @PostMapping(value = "testExam" )
    public ResultJson testExam(){
        return ResultJson.ok(iExamRecordService.testExam());
    }


    @ApiOperation(value = "阅卷管理 - gt_exam_record" )
    @PostMapping(value = "checkPaper" )
    public ResultJson checkPaper(@RequestBody ExamRecordParm frontPage){;
        Object list=iExamRecordService.selectExamRecordList(frontPage);
        return ResultJson.ok(list);
    }

    /**
     * 生成二维码方法
     *     接口给返   时间，单位名称，证书编号，二维码
     *     企业用户
     * @param  content 要生成的内容
     * @param resp response对象
     * @throws Exception 抛出异常
     */
    @ApiOperation(value = "生成二维码" )
    @PostMapping(value = "/qrcode")
    public ResultJson getQrcode(String content ,HttpServletResponse resp) throws Exception {
        ServletOutputStream stream = null;
       /* Long qrid=Long.parseLong(content);
        Ticket ticket=ticketRepository.findByTicketId(qrid);
       if (ticket!=null) {*/
        try {
            stream = resp.getOutputStream();
            Map<EncodeHintType, Object> hints = new HashMap<>();
            //编码
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            //边框距
            hints.put(EncodeHintType.MARGIN, 0);
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            String dateStr = DateUtil.format(LocalDateTime.now(),"yyyy-MM-dd HH:mm:ss");
            CertificateVO certificateVO = CertificateVO.builder().companyCode("HBJ").time(dateStr).index("11").build();
//            content = iExamRecordService.genCertificateEncoding("HBJ",dateStr,"11");
//            certificateVO.setCode(content);

            ExamRecordVO examRecordVO = ExamRecordVO.builder().build();
            examRecordVO.setMemberId(Integer.valueOf(content));
            Object t = iExamRecordService.queryCertificate(examRecordVO);


            BitMatrix bm = qrCodeWriter.encode(JSONUtil.toJsonStr(t), BarcodeFormat.QR_CODE, 200, 200, hints);
            MatrixToImageWriter.writeToStream(bm, "png", stream);
            return ResultJson.ok(certificateVO);
        } catch (WriterException e) {
            e.getStackTrace();

        } finally {
            if (stream != null) {
                stream.flush();
                stream.close();
            }
        }
        return ResultJson.ok();
    }
    @ApiOperation(value = "发放证书 - gt_exam_record" )
    @PostMapping(value = "sendCertificate" )
    public ResultJson sendCertificate(@RequestBody ExamRecordVO examRecordVO){
        return ResultJson.ok(iExamRecordService.sendCertificate(examRecordVO));
    }

    /**
     * 下发证书，需要得到  证书编号，获取时间，单位名称
     * 查询证书，需要得到二维码，获取时间，单位名称
     * @param examRecordVO
     * @return
     */
    @ApiOperation(value = "查询证书 - gt_exam_record" )
    @PostMapping(value = "queryCertificate" )
    public ResultJson queryCertificate(@RequestBody ExamRecordVO examRecordVO) throws Exception {
        Object t = iExamRecordService.queryCertificate(examRecordVO);

        return ResultJson.ok(t);
    }


}